package com.sky.task;


import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;
//    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行
//    public void executeTask(){
//        log.info("定时任务每分钟执行,{}",new Date());
//    }

    /**
     * 处理付款超时订单的方法，每分钟处理一次
     */
    @Scheduled(cron = "0 0/1 * * * ?") // 每分钟执行
    public void processTimeoutOrder(){
        log.info("处理付款超时订单,{}", LocalDateTime.now());

        // select * from orders where status = ? and order_time < localdatetime-15;
        List<Orders> ordersDBList = orderMapper.getByStatusAndOrderTime(Orders.PENDING_PAYMENT,LocalDateTime.now().plusMinutes(-15));
        if(ordersDBList != null && !ordersDBList.isEmpty())
        for (Orders ordersDB : ordersDBList) {
            Orders orders = new Orders();
            orders.setId(ordersDB.getId());
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason(Orders.TIMEOUTREASON);
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        }
    }

    /**
     * 定时处理处于派送中的订单，定时凌晨一点处理
     */
    @Scheduled(cron = "0 0 1 * * ? ") // 定z时凌晨一点处理
    public void processDeliveryOrder(){
        log.info("定时处理处于派送中的订单,{}", LocalDateTime.now());

        // select * from orders where status = ? and order_time < localdatetime-60;
        List<Orders> ordersDBList = orderMapper.getByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,LocalDateTime.now().plusMinutes(-60));
        if(ordersDBList != null && !ordersDBList.isEmpty())
            for (Orders ordersDB : ordersDBList) {
                Orders orders = new Orders();
                orders.setId(ordersDB.getId());
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
    }
}
